package com.cn.web.controller.bc;

import com.alibaba.fastjson2.JSONObject;

import com.cn.bean.pojo.bc.Mater;
import com.cn.bean.pojo.bc.MaterList;
import com.cn.bean.pojo.bc.UseClassify;
import com.cn.bean.pojo.bc.UseDefinition;
import com.cn.bean.vo.bc.Purposes;
import com.cn.bean.vo.bc.TreeNode;
import com.cn.config.config.Msg;
import com.cn.mapper.dao.db1.bc.PurposesDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@CrossOrigin
@RestController
public class PurposesController {
    private final PurposesDao purposesDao;

    @Autowired
    public PurposesController(PurposesDao purposesDao) {
        this.purposesDao = purposesDao;
    }

    @RequestMapping("/select/Purposes")
    @ResponseBody
    public Purposes selectPurposes(@RequestBody JSONObject jsonObject) {
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        String userName = jsonObject.getString("userName");
        Purposes purposes = new Purposes();
        List<UseClassify> useClassifies = purposesDao.selectUseClassify();
        List<UseDefinition> useDefinitions = purposesDao.pagination(limit, page);
        List<UseDefinition> downDefinitionList = purposesDao.selectUseDefinition();
        int definitionCount = purposesDao.getDefinitionCount();

        purposes.setDefinitionsList(useDefinitions);
        purposes.setDownDefinitionList(downDefinitionList);
        purposes.setClassifyList(useClassifies);
        purposes.setTotal(definitionCount);
        return purposes;
    }

    // 分页
    @RequestMapping("/select/Pagination")
    @ResponseBody
    public Purposes selectPagination(@RequestBody JSONObject jsonObject) {

        Integer limit = jsonObject.getInteger("limit");
        Integer page = jsonObject.getInteger("page");
        String flmc = jsonObject.getString("flmc");
        Purposes purposes = new Purposes();
        String userName = jsonObject.getString("userName");
        if (flmc.equals("用途分类")) {

            List<UseDefinition> pagination = purposesDao.pagination(limit, page);
            int total = pagination.get(0).getTotal();
            purposes.setTotal(total);
            purposes.setDefinitionsList(pagination);
            return purposes;
        }
        int total = 0;
        List<UseDefinition> useDefinitions = purposesDao.searchPagination(limit, page, "", "", flmc);
        if (!useDefinitions.isEmpty()) {
            total = useDefinitions.get(0).getTotal();
        }

        purposes.setTotal(total);
        purposes.setDefinitionsList(useDefinitions);
        return purposes;
    }

    //搜索框
    @RequestMapping("/search/Pagination")
    @ResponseBody
    public Purposes searchPagination(@RequestBody JSONObject jsonObject) {
        int limit = jsonObject.getInteger("limit");
        int page = jsonObject.getInteger("page");
        String ytbm = jsonObject.getString("inputBm");
        String ytmc = jsonObject.getString("inputMc");
        String userName = jsonObject.getString("userName");
        Purposes purposes = new Purposes();
        int total = 0;
        ytmc = (ytmc != null) ? ytmc : "";
        ytbm = (ytbm != null) ? ytbm : "";
        List<UseDefinition> useDefinitions = purposesDao.searchPagination(limit, page, ytmc, ytbm, "");

        if (!useDefinitions.isEmpty()) {
            total = useDefinitions.get(0).getTotal();
        }
        purposes.setTotal(total);
        purposes.setDefinitionsList(useDefinitions);
        return purposes;
    }

    //   点击侧边栏触发事件
    @RequestMapping("/select/Definition/flmc")
    @ResponseBody
    public Purposes selectUseDefinitionFlmc(@RequestBody JSONObject jsonObject) {
        int limit = jsonObject.getInteger("limit");
        int page = jsonObject.getInteger("page");
        String ytbm = "";
        String ytmc = "";
        String flmc = jsonObject.getString("flmc");
        Integer id = jsonObject.getInteger("id");
        int total = 0;
        Purposes purposes = new Purposes();
        if (flmc.equals("用途分类")) {
            List<UseDefinition> useDefinitions = purposesDao.pagination(limit, page);
            total = useDefinitions.get(0).getTotal();
            purposes.setTotal(total);
            purposes.setDefinitionsList(useDefinitions);
            return purposes;
        }
        //当前分类
        UseClassify useClassify = purposesDao.selectClassifyId(id);
        //所有分类
        List<UseClassify> useClassifies = purposesDao.selectUseClassify();
        //所有定义
        List<UseDefinition> useDefinitions = purposesDao.selectUseDefinition();
        List<UseClassify> subcategories = getSubcategories(useClassifies, id);
        List<UseDefinition> categorizedDys = getCategorizedDys(useDefinitions, subcategories);

        purposes.setDefinitionsList(categorizedDys);
        purposes.setUseClassify(useClassify);
        return purposes;
    }
    private List<UseDefinition> getCategorizedDys(List<UseDefinition> allDys, List<UseClassify> categories) {
        List<UseDefinition> categorizedDys = new ArrayList<>();

        for (UseDefinition dy : allDys) {
            for (UseClassify category : categories) {
                if (dy.getFq() == category.getId()) {
                    categorizedDys.add(dy);
                    break;  // 如果匹配到当前分类，就不需要再继续查找
                }
            }
        }
        return categorizedDys;
    }
    private List<UseClassify> getSubcategories(List<UseClassify> allCategories, int parentFlId) {
        List<UseClassify> subcategories = new ArrayList<>();
        for (UseClassify category : allCategories) {
            if (category.getParentBh() == parentFlId) {
                subcategories.add(category);
                List<UseClassify> children = getSubcategories(allCategories, category.getYtflbh());
                subcategories.addAll(children);
            } else if (category.getYtflbh() == parentFlId) {
                // 如果当前分类就是目标分类，也将其添加到列表中
                subcategories.add(category);
            }
        }
        return subcategories;
    }


    //修改分类
    @RequestMapping("/update/Classify")
    @ResponseBody
    public Msg updateClassify(@RequestBody JSONObject jsonObject) {
        int ytflbh = jsonObject.getInteger("ytflbh");
        String flmc = jsonObject.getString("flmc");
        int state = jsonObject.getInteger("state");
        String remark = jsonObject.getString("remark");
//        String ytfl = jsonObject.getString("ytfl");
        Integer ytfl = jsonObject.getInteger("ytfl");
        //验证flmc有没有修改
        UseClassify selectUseClassifyId = purposesDao.selectUseClassifyId(ytflbh);
        String flmc1 = selectUseClassifyId.getFlmc();
        Msg msg = new Msg();
        String userName = jsonObject.getString("userName");
        if (flmc.equals(flmc1)) {
            if (ytfl!=null) {
                UseClassify useClassify = purposesDao.selectClassifyId(ytfl);
//                UseClassify useClassify = purposesDao.selectParentId(ytfl);
                int level = useClassify.getLevel() + 1;
                int id = useClassify.getYtflbh();
                int i = purposesDao.updateClassify(ytflbh, flmc, state, remark, level, id);
                if (i > 0) {
                    msg.setCode(200);
                    msg.setMessage("修改成功");
                    return msg;
                }
                msg.setCode(500);
                msg.setMessage("修改失败");
            }
            int i = purposesDao.updateClfy(ytflbh, flmc, state, remark);
            if (i > 0) {
                msg.setCode(200);
                msg.setMessage("修改成功");
                return msg;
            }
            msg.setCode(500);
            msg.setMessage("修改失败");
            return msg;
        }
        if (ytfl==null) {
            Integer ifRepeat = purposesDao.repeatFlmcLevel(flmc, 1);
            if (ifRepeat > 0) {
                msg.setCode(500);
                msg.setMessage("分类名称在同一层级名称重复");
                return msg;
            }
            int i = purposesDao.updateClfy(ytflbh, flmc, state, remark);
            if (i > 0) {
                msg.setCode(200);
                msg.setMessage("修改成功");
                return msg;
            }
            msg.setCode(500);
            msg.setMessage("修改失败");
            return msg;
        }

        UseClassify useClassify = purposesDao.selectClassifyId(ytfl);
        Integer ifRepeat = purposesDao.repeatFlmcLevel(flmc, useClassify.getLevel()+1);
        if (ifRepeat > 0) {
            msg.setCode(500);
            msg.setMessage("分类名称在同一层级名称重复");
            return msg;
        }
        int level = useClassify.getLevel() + 1;
        int id = useClassify.getYtflbh();
        int i = purposesDao.updateClassify(ytflbh, flmc, state, remark, level, id);
        if (i > 0) {
            msg.setCode(200);
            msg.setMessage("修改成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("修改失败");
        return msg;
    }
    //  添加分类
    @RequestMapping("/insert/Classify")
    @ResponseBody
    public Msg insertClassify(@RequestBody JSONObject jsonObject) {
        String flmc = jsonObject.getString("flmc");
        int state = jsonObject.getIntValue("state");
        String remark = jsonObject.getString("remark");
        //上级分类
//        String parentCategory = jsonObject.getString("parentCategory");
        //上级分类的id
        Integer parentCategory = jsonObject.getInteger("parentCategory");
        Msg msg = new Msg();
        String userName = jsonObject.getString("userName");
        int ytflbh = purposesDao.getClassifyCount() + 1;
        if (parentCategory==null) {
            Integer result = purposesDao.repeatFlmc(flmc);
            if (result != null && result > 0) {
                msg.setCode(500);
                msg.setMessage("分类名称在同一层级名称重复");
                return msg;
            }
            int isOK = purposesDao.insertClassify(ytflbh, flmc, state, remark, 1, 1, 0);
            if (isOK > 0) {
                msg.setCode(200);
                msg.setMessage("添加成功");
                return msg;
            }
            msg.setCode(500);
            msg.setMessage("添加失败");
            return msg;
        }
//        UseClassify useClassify = purposesDao.selectParentId(parentCategory);
        UseClassify useClassify = purposesDao.selectClassifyId(parentCategory);
        int level = useClassify.getLevel() + 1;
        Integer ifRepeat = purposesDao.repeatFlmcLevel(flmc, level);
        if (ifRepeat != null && ifRepeat > 0) {
            msg.setCode(500);
            msg.setMessage("分类名称在同一层级名称重复");
            return msg;
        }

        int parentBh = useClassify.getYtflbh();
        int i1 = purposesDao.insertClassify(ytflbh, flmc, state, remark, level, parentBh, 0);
        if (i1 > 0) {
            msg.setCode(200);
            msg.setMessage("添加成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("添加失败");
        return msg;
    }

    //删除分类
    @RequestMapping("/delete/Classify")
    @ResponseBody
    public Msg deleteClassify(@RequestBody JSONObject jsonObject) {
        Msg msg = new Msg();
        int ytflbh = jsonObject.getInteger("ytflbh");
        //判断删除的权限
        String userName = jsonObject.getString("userName");
        //删除分类前验证，是否拥有子节点，有就无法删除
        Integer i1 = purposesDao.repeatClassifyParentBh(ytflbh);
        if (i1 > 0) {
            msg.setCode(500);
            msg.setMessage("请先删除这个分类的子节点");
            return msg;
        }
        int i = purposesDao.deleteClassify(String.valueOf(ytflbh));
        if (i > 0) {
            msg.setCode(200);
            msg.setMessage("删除成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("删除失败");
        return msg;
    }

    //添加用途
    @RequestMapping("/insert/Definition")
    @ResponseBody
    public Msg insertUseDefinition(@RequestBody JSONObject jsonObject) {
        Msg msg = new Msg();
//        String ytfl = jsonObject.getString("ytfl");
        Integer ytfl = jsonObject.getInteger("ytfl");
        String ytmc = jsonObject.getString("ytmc");
        int state = jsonObject.getIntValue("state");
        String remark = jsonObject.getString("remark");
        //添加用途的权限
        String userName = jsonObject.getString("userName");
        int ytbm = purposesDao.getDefinitionCount() + 1;
        //上级分类
//        UseClassify useClassify = purposesDao.selectYtfl(ytfl);
        UseClassify useClassify = purposesDao.selectClassifyId(ytfl);
        int fq = useClassify.getId();
        int isOK = purposesDao.insertUseDefinition(ytbm,useClassify.getFlmc(), ytmc, state, remark, 0, fq, 0, 1);
        if (isOK > 0) {
            msg.setCode(200);
            msg.setMessage("添加成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("添加失败");
        return msg;
    }

    //修改用途
    @RequestMapping("/update/Definition")
    @ResponseBody
    public Msg updateUseDefinition(@RequestBody JSONObject jsonObject) {
        int ytbm = jsonObject.getInteger("ytbm");
//        String ytfl = jsonObject.getString("ytfl");
        Integer ytfl = jsonObject.getInteger("ytfl");
        System.out.println("分类："+ytfl);
        String ytmc = jsonObject.getString("ytmc");
        int state = jsonObject.getInteger("state");
        String remark = jsonObject.getString("bz");
        Msg msg = new Msg();
        UseClassify useClassify = purposesDao.selectClassifyId(ytfl);
        int fq = useClassify.getId();
        int i = purposesDao.updateUseDefinition(ytbm, useClassify.getFlmc(), ytmc, state, remark, fq);
        if (i > 0) {
            msg.setCode(200);
            msg.setMessage("修改成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("修改失败");
        return msg;
    }

    @RequestMapping("/delete/Definition")
    @ResponseBody
    public Msg deleteDefinition(@RequestBody JSONObject jsonObject) {
        String ytmc = jsonObject.getString("ytmc");
        Msg msg = new Msg();
        int i = purposesDao.deleteDefinition(ytmc);
        if (i > 0) {
            msg.setCode(200);
            msg.setMessage("删除成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("删除失败");
        return msg;
    }

    @RequestMapping("/update/State0")
    @ResponseBody
    public Msg updateState0(@RequestBody JSONObject jsonObject) {
        String ytmc = jsonObject.getString("ytmc");
        Msg msg = new Msg();
        int i = purposesDao.updateState0(ytmc);
        if (i > 0) {
            msg.setCode(200);
            msg.setMessage("审核成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("审核失败!");
        return msg;
    }

    @RequestMapping("/update/State1")
    @ResponseBody
    public Msg updateState1(@RequestBody JSONObject jsonObject) {
        String ytmc = jsonObject.getString("ytmc");
        Msg msg = new Msg();
        int i = purposesDao.updateState1(ytmc);
        if (i > 0) {
            msg.setCode(200);
            msg.setMessage("弃审成功");
            return msg;
        }
        msg.setCode(500);
        msg.setMessage("弃审失败!");
        return msg;
    }



    //    树状结构
    @RequestMapping("/select/get/Purposes")
    @ResponseBody
    public List<TreeNode> selectGetPurposes() {
        List<Purposes> purposesList = purposesDao.getPurposes();
        return convertToTreeData(purposesList);
    }

    // 递归方法将 Purposes 转换为 TreeNode
    private List<TreeNode> convertToTreeData(List<Purposes> purposesList) {
        List<TreeNode> treeData = new ArrayList<>();

        for (Purposes purpose : purposesList) {
            TreeNode treeNode = getTreeNode(purpose);
            // 如果存在子节点，则递归处理子节点
            if (purpose.getDparentBh() != 0 && purpose.getDlevel() == 1) {
                treeData.add(treeNode);
            } else {
                // 不是主节点，找到对应的父节点并添加为子节点
                addNodeToParent(treeData, treeNode, purpose.getDlevel());
            }
        }

        return treeData;
    }

    private static TreeNode getTreeNode(Purposes purpose) {
        TreeNode treeNode = new TreeNode();
        treeNode.setId(purpose.getYtbm());
        treeNode.setFlmc(purpose.getFlmc());
        treeNode.setRlevel(purpose.getRlevel());
        treeNode.setRarentBh(purpose.getRparentBh());
        treeNode.setDarentBh(purpose.getDparentBh());
        treeNode.setDlevel(purpose.getDlevel());
        treeNode.setYtbm(purpose.getYtflbh());
        treeNode.setYtfl(purpose.getYtfl());
        treeNode.setYtmc(purpose.getYtmc());
        treeNode.setState(purpose.getState() == 0 ? "启用" : "停用");
        treeNode.setRemark(purpose.getRemark());
        treeNode.setFq(purpose.getFq());
        return treeNode;
    }

    private void addNodeToParent(List<TreeNode> treeData, TreeNode childNode, int parentDlevel) {
        for (TreeNode parentNode : treeData) {
            if (childNode.getDarentBh() != 0 && childNode.getFq() == parentNode.getId()) {
                if (parentNode.getChildren() == null) {
                    parentNode.setChildren(new ArrayList<>());
                }
                parentNode.getChildren().add(childNode);

                // 根据 parentDlevel 决定是否继续递归
                if (childNode.getDlevel() > parentDlevel) {
                    // 继续递归添加子节点
                    addNodeToParent(parentNode.getChildren(), childNode, childNode.getDlevel());
                }

                // 这里不再进行额外的比较
                break;
            }
        }
    }
}
